import Log from '../../utils/log';
import Toast from 'tdesign-miniprogram/toast/index';
import ActionSheet, {
  ActionSheetTheme
} from 'tdesign-miniprogram/action-sheet/index';
import commondUtil from '../../utils/commondUtil';
import SignClient from "../../api/modules/signClient";
import Sign from "../../api/modules/sign";

Page({
  data: {
    signClientList: [],
    currentSelectedCilent: null,
    lastRequestTime: null,
    requestLoading: false,
  },

  onShow() {
    // 超过30s切换至该界面刷新数据
    if ((Date.now() - this.data.lastRequestTime) > 30000) {
      this.getClientInfo();
    }
  },

  getClientInfo() {
    if (this.data.requestLoading) {
      return;
    }
    this.setData({
      currentSelectedCilent: null,
      requestLoading: true,
    });
    SignClient.getUserSignClient().then((resp) => {
      const data = resp.data;
      if (commondUtil.isEmpty(data)) {
        return;
      }
      data.forEach(item => {
        if (commondUtil.isNotEmpty(item.lastOnlineTime) && commondUtil.isEmpty(item.onlineFlag)) {
          const lastOnlineDate = commondUtil.parserDate(item.lastOnlineTime);
          item.onlineFlag = Math.abs(new Date() - lastOnlineDate) < 120000
        }

        if (commondUtil.isNotEmpty(item.autoSignTime)) {
          item.autoSignTime = commondUtil.formatDate(item.autoSignTime, true, false).substring(11);
        }
      });
      this.setData({
        signClientList: data
      });
    }).finally(() => {
      this.setData({
        lastRequestTime: Date.now(),
        enable: false,
        requestLoading: false,
      });
    });
  },

  onActionClick(e) {
    const clientInfo = e.currentTarget.dataset.item;
    this.setData({
      currentSelectedCilent: clientInfo
    });
    const userInfo = wx.getStorageSync('userInfo');
    const btnList = [{
        id: 'signRecord',
        label: '签到记录',
      },
      {
        id: 'detail',
        label: '客户端详情',
      }
    ];
    if (clientInfo.onlineFlag) {
      btnList.push({
        id: 'execSign',
        label: '发送签到指令',
      });
      if (clientInfo.createCode == userInfo.id) {
        btnList.push({
          id: 'ignoreTodaySign',
          label: '忽略当天签到',
        }, {
          id: 'disconnectClient',
          label: '关闭客户端连接',
        });
      }
    }
    ActionSheet.show({
      theme: ActionSheetTheme.List,
      selector: '#t-action-sheet',
      context: this,
      items: btnList,
    });
  },

  onDelete(e) {
    const clientInfo = e.currentTarget.dataset.item;
    wx.showModal({
      title: '提示',
      content: '确定要删除该客户端吗？',
      success: (data) => {
        if (data.cancel || !data.confirm) {
          return;
        }
        SignClient.invalid({
          clientId: clientInfo.id
        }).then((resp) => {
          Toast({
            context: this,
            selector: '#t-toast',
            message: `删除${resp.data ? '成功' : '失败'}`,
            theme: resp.data ? 'success' : 'warning',
            direction: 'column',
          });
          if (resp.data) {
            this.getClientInfo();
          }
        }).catch((e) => {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '删除失败,请查看日志',
            theme: 'error',
            direction: 'column',
          });
          Log.errorAll("删除客户端失败! clientId: ", clientInfo.id, e);
        });
      }
    });
  },
  onEdit(e) {
    const clientInfo = e.currentTarget.dataset.item;
    const userInfo = wx.getStorageSync('userInfo');
    if (clientInfo.createCode !== userInfo.id) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '非创建人不可编辑',
        theme: 'warning',
        direction: 'column',
      });
      return;
    }
    this.setData({
      currentSelectedCilent: clientInfo
    });
    this.jumpToCilentInfoPage(true);
  },

  handleSelected(e) {
    if (this.data.currentSelectedCilent == null) {
      return;
    }
    const id = e.detail.selected.id;
    switch (id) {
      case 'signRecord':
        wx.navigateTo({
          url: '/pages/signRecord/signRecord',
          success: (res) => {
            res.eventChannel.emit('delivery', {
              clientInfo: this.data.currentSelectedCilent
            });
          }
        });
        break;
      case 'detail':
        this.jumpToCilentInfoPage(false);
        break;
      case 'execSign':
        this.handleExecSign();
        break;
      case 'ignoreTodaySign':
        this.handleIgnoreTodaySign();
        break;
      case 'disconnectClient':
        this.handleDisconnectClien();
        break;
      default:
        break;
    }
  },
  handleExecSign() {
    wx.showModal({
      title: '提示',
      content: '确定发送签到指令吗？',
      success: (data) => {
        if (data.cancel || !data.confirm) {
          return;
        }
        this.sendCilentOpratorRequest('execSign', '发送签到指令成功').then(signRecordId => {
          if (typeof signRecordId == 'boolean' || commondUtil.isBlank(signRecordId)) {
            return;
          }
          wx.showModal({
            title: '提示',
            content: '发送签到指令成功，是否跳转查看签到过程？',
            success: (data) => {
              if (data.cancel || !data.confirm) {
                this.getClientInfo();
                return;
              }
              wx.navigateTo({
                url: '/pages/signRecordDetail/signRecordDetail',
                success: (res) => {
                  res.eventChannel.emit('delivery', {
                    pageClientName: `${this.data.currentSelectedCilent.clientName}-page-${signRecordId}-wx-${commondUtil.uuid()}`
                  });
                }
              });
            }
          });
        });
      }
    });
  },
  handleIgnoreTodaySign() {
    wx.showModal({
      title: '提示',
      content: '确定忽略当天签到吗？',
      success: (data) => {
        if (data.cancel || !data.confirm) {
          return;
        }
        this.sendCilentOpratorRequest('ignoreTodaySign', '忽略当天签到成功').then(flag => {
          if (flag) {
            this.getClientInfo();
          }
        });
      }
    });
  },
  handleDisconnectClien() {
    wx.showModal({
      title: '提示',
      content: '确定要关闭客户端连接吗？',
      success: (data) => {
        if (data.cancel || !data.confirm) {
          return;
        }
        this.sendCilentOpratorRequest('disconnectClient', '关闭客户端连接成功').then(flag => {
          if (flag) {
            this.getClientInfo();
          }
        });
      }
    });
  },

  sendCilentOpratorRequest(apiName, successTip) {
    return new Promise((resolve) => {
      if (this.data.currentSelectedCilent == null) {
        resolve(false);
        return;
      }
      Sign[apiName]({
        clientName: this.data.currentSelectedCilent.clientName
      }).then(resp => {
        if (!resp.data) {
          Toast({
            context: this,
            selector: '#t-toast',
            message: resp.message,
            theme: 'error',
            direction: 'column',
          });
          resolve(false);
          return;
        }
        Toast({
          context: this,
          selector: '#t-toast',
          message: successTip,
          theme: 'success',
          direction: 'column',
        });
        resolve(resp.data);
      }).catch(e => {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '发送客户端命令失败',
          theme: 'error',
          direction: 'column',
        });
        Log.errorAll("发送客户端命令失败", e);
      });
    });
  },
  jumpToCilentInfoPage(editFlag = false) {
    wx.navigateTo({
      url: '../signClientInfo/signClientInfo',
      success: (res) => {
        res.eventChannel.emit('delivery', {
          clientInfo: this.data.currentSelectedCilent,
          editFlag: editFlag
        });
      },
      events: {
        refreshSignClient: () => {
          this.getClientInfo();
        }
      }
    });
  },
  bindUserSignClient() {
    this.setData({
      currentSelectedCilent: null
    });
    this.jumpToCilentInfoPage(true);
  },

  onRefresh() {
    this.setData({
      enable: true
    });
    this.getClientInfo();
  },

})